package RobotPlayer
{
	import adobe.utils.CustomActions;
	import BasicEngine.Dispatcher;
	import BasicEngine.Vector2D;
	import DataStore.BmpDataPool;
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.geom.Point;
	import flash.text.TextField;
	import flash.utils.Dictionary;
	import GameLogic.Game;
	import GameLogic.ScanBeam;
	import SoundManager.SoundFactory;
	public class BaseRobot extends MoveEntity
	{
		/**
		 * 显示名称
		 */
		public var ShowName:TextField;
		
	   	/**
		 * 模块索引
		 */		
		public var Modules:Dictionary;
		
		/**
		 * 雷达
		 * 机器人的雷达只包括雷达光束
		 */
		public var Radar:ScanBeam;
		
		/**
		 * 健康值
		 */
		public var Hp:int;
		
		/**
		 * 锁定雷达
		 */
		public var LockRadar:Boolean;
		/**
		 * 锁定上部模块
		 */
		public var LockTop:Boolean = false;
		
		/**
		 * 隐藏雷达
		 */
		public var HideRadar:Boolean;
		
		/**
		 * CD时间，有装配不同的武器来决定
		 */
		public var CdTime:int;
		
		/**
		 * 用于检测碰撞的半径
		 */
		public var CollisionRadius:int = 30;
		/**
		 * 是否是玩家的坦克
		 */
		public var IsHero:Boolean = false;
		
		/**
		 * 发动机的力
		 */
		public var Force:Vector2D;
		
		/**
		 * 炮塔转速
		 */
		public var BarbetteRote:Number = 0.3;
		/**
		 * 炮塔转动方向 (true:顺时针 false:逆时针)
		 */
		public var BarbetteRoteDirect:Boolean;
		/**
		 * 保持炮塔当前指向
		 */
		public var KeepBarbetteDirc:Boolean;
		/**
		 * 炮塔目标指向
		 */
		public var BarbetterTarget:Vector2D;
		
		public var Targets:Dictionary;
		/**
		 * 锁定目标
		 */
		public var LockTarget:BaseRobot;
		
		public var Hpline:Hpgauge;
		
		public var targetT:Vector2D;
		
		public var Explode:Boolean;
		
		/**
		 * 合力
		 */
		public var resultant:Resultant;
		
		public var Running:Boolean = false;
		
		public var target:Vector2D = new Vector2D(300, 300);
		
	
		
		private var shape:Shape;
		
		/**
		 * 是否显示辅助框
		 * 红色表示碰撞框
		 */
		private var showAssist:Boolean;
		private var AssistBorder:Shape;
		
		
		public var foot:int = 0;
		
		public var radarVector:Vector2D =  new Vector2D(1, 1);
		
		
		public var lv:Vector2D ;
		public var tv:Vector2D;
		public var bv:Vector2D;
		
		public var limitTime:int;
		
		
		/**
		 * _velocity:Vector2D 初始速度 _mass:Number 质量 _maxSpeed:Number 最大速度 _maxForce:Number 最大受力 _scale:Number 缩放比（默认为1）
		 */
		public function BaseRobot (_velocity:Vector2D,
								   _mass:Number,
								   _maxSpeed:Number,
								   _maxForce:Number,
								   _scale:Number = 1.0
								)
		{
			super(_velocity, _mass, _maxSpeed, _maxForce);
			Canvas = new Sprite();
			Scale = _scale;
			Modules = new Dictionary();
			resultant = new Resultant(this);
			Force = new Vector2D();
			Radar = new ScanBeam(this, 0x00ffff, 500, 0.2, 0.15);
			
			BarbetterTarget = new Vector2D(1, 1).Normalize();
			KeepBarbetteDirc = true;
			
			radarVector.Normalize();
			radarVector.Angle = Velocity.Angle;
			
			Targets = new Dictionary();
			Running = false;
			
			Canvas.addEventListener(Event.ENTER_FRAME, Update);
			
			
			shape = new Shape();
			shape.graphics.beginFill(0xff0000, 1);
			shape.graphics.drawCircle(0, 0, 2);
			Game.Building.addChild(shape);
			shape.x = target.X;
			shape.y = target.Y;
			//shape.visible = false;
			
			DrawAssistBorder();
			
			ShowName = new TextField();
			ShowName.textColor = 0xffffff;
			Canvas.addChild(ShowName);
			ShowName.y = -45;
			ShowName.x = -30;
			ShowName.height = 21;
			ShowName.text = ID.toString();
			
			Hpline =  new Hpgauge(1000);
		    Canvas.addChild(Hpline);
			Hp = 1000;
			Hpline.x = -30;
			Hpline.y = -28;
		}
		
		/**
		 * 装配模块
		 */
		public function AssemblyModule(_module:RobotModule,_x:int = 0, _y:int = 0):void
		{
			Modules[_module.Name] = _module;
			Canvas.addChild(_module.Canvas);
			_module.Canvas.x = _x;
			_module.Canvas.y = _y;
		}

		public function SetTarget(_x:Number, _y:Number):void
		{
			target.X = _x;
			target.Y = _y;
		}
		
		public function Run():void
		{
			Running = true;
		}
		
		public function Stop():void
		{
			Running = false;
		}
		
		public function Dispose():void
		{
			Canvas.removeEventListener(Event.ENTER_FRAME, Update);
		}
		
		public function FireOne():void
		{
			Fire(Pos.X, Pos.Y, Modules["TopModule"].Heading.Angle);
		}
		
		public function FireThree():void
		{
			Fire(Pos.X, Pos.Y, Modules["TopModule"].Heading.Angle);
			Fire(Pos.X, Pos.Y, Modules["TopModule"].Heading.Angle+0.1);
			Fire(Pos.X, Pos.Y, Modules["TopModule"].Heading.Angle-0.1);
		}
				
		/**
		 * 发射火箭
		 */
		private function Fire(_x:int,_y:int,_angle:Number):void
		{
			var M:BaseMissile = new BaseMissile(this,new Vector2D(0,0),500,10,1220,new Point(0, 0), new Point(0, 29), [5004, 5005, 5006, 5007],[5000, 5001, 5002, 5003] );
			M.Pos.X = _x;
			M.Pos.Y = _y;
			M.SendAngle = _angle;
			CdTime += 2000;
		}
		
		private function Update(e:Event):void
		{
			HideAssistLine();
			if (Game.Pause)
			   return;
			   
			TraverseRobots();
						   
			if (Game.LuaEdit.CircleRun.selected)
				Game.LuaAl.doString(Game.LuaEdit.input.text);

			UpdateFinal();   
			
			if (!Running)
			   return;
			
			MoveEngine();
			
			lv = Game.WorldToLocal(target, this.Pos, Heading);   
			tv = Game.WorldToLocal(targetT, this.Pos, Radar.RadarAngle);
			bv = Game.WorldToLocal(targetT, this.Pos, BarbetterTarget);
			
			UpdateBarbette();	
			
			RadarTraverseRobots();
			
			TouchTarget();
		}
		/**
		 * 返回相对坐标
		 */
		public function ToWordCoordinate(_point:Vector2D):Vector2D
		{
			var l:Vector2D = Game.WorldToLocal(_point, Pos, Heading);
			return l;
		}
		/**
		 * 返回发动机的力
		 */
		public function SetForce():void
		{
			//return resultant.Arrive(target);
			//return resultant.Seek(target);
			Force = resultant.Seek(target);
		}
		
		public function GetX():int
		{
			return Pos.X;
		}
		
		public function GetY():int
		{
			return Pos.Y;
		}
		
		public function GetHeading():Number
		{
			return Heading.Angle;
		}
		
		/**
		 * 被击中事件
		 */
		public function MissileExplode(_type:BaseMissile):void
		{
			Game.LuaAl.doString(Game.LuaScriptApiSt["OnMissileRaid()"]);
		}
		
		public function SetMass(_fact:Number):void
		{
			if (_fact >= 5)
			  Mass = Mass + (_fact - 5) * Mass;
			else
			  Mass = Mass / (6 - _fact);
		}
		
		private function DrawAssistBorder():void
		{
		    AssistBorder = new Shape();
			AssistBorder.graphics.lineStyle(1, 0xff0000);
			AssistBorder.graphics.moveTo(0, 0);
			AssistBorder.graphics.drawCircle(0, 0, CollisionRadius);
			Canvas.addChild(AssistBorder);
			AssistBorder.graphics.beginFill(0xffffff, 1);
			AssistBorder.graphics.drawCircle(0, 0, 10);
		}
		
		/**
		 * 雷达炮塔联动
		 * 搜索目标，转动炮塔指向目标，开火
		 */
		private function UpdateBarbette():void
		{
			//雷达发现目标后,炮塔解锁,开始转动
			if( Math.abs(tv.Angle * 180/Math.PI) < 10) 
			{
				Game.ShowRadar.P.Angle = lv.Angle - Math.PI / 2;
				Game.ShowRadar.P.Length = lv.Length /9;
				Game.ShowRadar.shape.visible = true;
				Radar.Action = 0;				
				KeepBarbetteDirc = false;
			}
			else
			{
				Radar.Action = 1;
			}
			//如果炮塔指向目标,加锁,不再转动
			
			if( Math.abs(bv.Angle * 180/Math.PI) < 10) 
			{
				KeepBarbetteDirc = true;
				if (CdTime <= 0)
				{
					FireOne();				   
				}
			}
			//如果炮塔解锁,转动
			if (!KeepBarbetteDirc)
			{
				BarbetterTarget.Angle += BarbetteRote;
			}
		}
		
		private function  HideAssistLine():void
		{
			Radar.visible = Game.SetButton.SettingPanel.radarline.selected;
			AssistBorder.visible = Game.SetButton.SettingPanel.assistLine.selected;
			(Modules["TopModule"] as RobotModule).AssistBorder.visible = Game.SetButton.SettingPanel.topCoor.selected;
			(Modules["BottomModule"] as RobotModule).AssistBorder.visible = Game.SetButton.SettingPanel.bottomCoor.selected;
		}
		
		/**
		 * 接触目标
		 */
		private function TouchTarget():void
		{
			if (Math.abs(Pos.X - target.X) < 20 && Math.abs(Pos.Y - target.Y) < 20)
			{
			if(Game.SetButton.SettingPanel.turnoffSound.selected)
				SoundFactory.Sounds["sound16"].play();

				target.X = Math.random() * 500 + 50;
				target.Y = Math.random() * 400 + 50;
				
				shape.x = target.X;
			    shape.y = target.Y;
			}
			
			if (Pos.X <= 0 || Pos.X > 760 || Pos.Y <= 0 || Pos.Y >= 560)
			{
				Velocity.Length = 0;
			}
		}
		
		private function MoveEngine():void
		{
			SetForce();
			var acceleration:Vector2D = Force.CrossProduct(1.0/Mass);
			var vTemp:Vector2D = acceleration.CrossProduct(Dispatcher.Clock.Tick);
			Velocity =  Velocity.Addition(vTemp); 	
			Velocity.Turncate(MaxSpeed);
			var pTemp:Vector2D = Velocity.CrossProduct(Dispatcher.Clock.Tick);
			Pos = Pos.Addition(pTemp);	
			if (Velocity.LengthSQ > 0.000001)
			{
				Heading = Velocity.NormalizeClone();
				Side = Heading.Perp;
			}
		}
		
		private function UpdateFinal():void
		{
			Canvas.x = Pos.X;
			Canvas.y = Pos.Y;
			
			Modules["BottomModule"].Heading.Angle = Velocity.NormalizeClone().Angle ;
			Modules["TopModule"].Heading.Angle = BarbetterTarget.Angle - Math.PI / 2;
	
			CdTime -= 10;	
			Hpline.SetHp(Hp);
			
			if (Hp <= 0)
			{
				RobotFactory.RemoveRobot(ID);
				var ex2:BaseExplode = new BaseExplode(Game.PlayerCanvas, [5012,5013, 5014, 5015, 5016, 5017], 60, 1);
				ex2.x = Pos.X;
				ex2.y = Pos.Y;
			}
		}
		
		/**
		 * 遍历其他机器人
		 */
		private function TraverseRobots():void
		{
			var ro:BaseRobot;
			var l:Number = 0;
			for each(var item:BaseRobot in RobotFactory.RobotRecords)
			{
				if (ID != item.ID)
				{
					var ll:Number = (Pos.X - item.Pos.X) * (Pos.X - item.Pos.X) + (Pos.Y - item.Pos.Y) * (Pos.Y - item.Pos.Y);
				    if ( ll > l)
				    {
				    	l = ll;
				    	ro = item;
				    }
				}
			}
			if(ro != null)
			   targetT = ro.Pos;
			else
			   targetT = target;
		}
		
		
		/**
		 * 雷达扫描遍历其他机器人
		 */
		private function RadarTraverseRobots():void
		{
		   for each(var item:BaseRobot in RobotFactory.RobotRecords)
			 {
			 	if (ID != item.ID)
			 	{
			 		var tv:Vector2D = Game.WorldToLocal(item.Pos, Pos, Radar.RadarAngle);
			 		if ( Math.abs(tv.Angle * 180 / Math.PI) < 10) 
			 		{
			 			Game.LuaAl.doString(Game.LuaScriptApiSt["OnRadarScan()"]);
			 		}
			 	}
			 }
		}
		
	}
}